﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using System.Data;

namespace DataExtractionLanguage
{
    public class ExecutionUnit
    {
        private readonly Report report;
        private SelectStatement currentSelectStat;
        List<DataTable> selectsResult = new List<DataTable>();

        public ExecutionUnit(Report report)
        {
            this.report = report;
        }

        public DataTable Execute(List<SelectStatement> instructions)
        {
            foreach (SelectStatement selInst in instructions)
            {
                currentSelectStat = selInst;
                selInst.From.FirstDataExtraction(selInst.ActualColumns);
                DataTable dt = selInst.Select();
                UnifySelectResult(dt);
            }

            return UnionResult();
        }

        private DataTable UnionResult()
        {
            DataTable retTbl = new DataTable("Result");
            foreach (DataColumn clm in selectsResult[0].Columns)
                retTbl.Columns.Add(clm.ColumnName, clm.DataType, clm.Expression);

            foreach (DataTable tbl in selectsResult)
                foreach (DataRow row in tbl.Rows)
                    retTbl.Rows.Add(row.ItemArray);

            return retTbl;
        }

        private void UnifySelectResult(DataTable tbl)
        {
            if (selectsResult.Count == 0)
            {
                selectsResult.Add(tbl);
            }
            else
            {
                DataTable lastTbl = selectsResult[selectsResult.Count - 1];
                if (lastTbl.Columns.Count != tbl.Columns.Count)
                    report.Error("columns count of select statements is not equal", "");
            }
        }
    }
}